package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.service.admin.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;
import java.util.Objects;

@Service("adminEmployeeService")
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    private final EmployeeMapper employeeMapper;

    @Autowired
    public EmployeeServiceImpl(EmployeeMapper employeeMapper) {
        this.employeeMapper = employeeMapper;
    }



    /**
     * 新增员工
     *
     * @param employeeDTO 员工信息DTO
     */
    @Override
    public void saveEmployee(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        //对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);

        //设置账号的状态, 默认正常状态, 1表示正常,0为锁定
        //利用常量类中的值修改属性,方便后期维护
        employee.setStatus(StatusConstant.ENABLE);

        //新增密码, 默认密码为123456
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        //设置当前记录的创建时间和修改时间
//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());

        //设置当前记录创建人Id和修改人Id
        //因为暂时无法获取到创建人Id和修改人Id, 暂时拿常量代替(暂时无法实现的功能用TODO)
//        employee.setCreateUser(BaseContext.getCurrentId());
//        employee.setUpdateUser(BaseContext.getCurrentId());

        //注入持久层
        employeeMapper.insertEmployee(employee);
    }

    /**
     * 删除指定id员工
     *
     * @param employeeId id
     */
    @Override
    public void deleteEmployee(Long employeeId) {
            employeeMapper.deleteEmployeeById(employeeId);
    }

    /**
     * 修改员工信息
     *
     * @param employeeDTO 员工实体类DTO
     */
    @Override
    public void updateEmployee(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);
        employeeMapper.updateEmployee(employee);
    }

    /**
     * 启用或者禁用员工账号
     *
     * @param status     账号状态
     * @param employeeId 员工id
     */
    @Override
    public void startOrStopEmployee(Integer status, Long employeeId) {
        Employee employee = Employee.builder()
                .id(employeeId)
                .status(status)
                .build();
        employeeMapper.updateEmployee(employee);
    }

    /**
     * 分页查询员工数据
     *
     * @param employeePageQueryDTO 员工数据DTO
     * @return 分页查询实体类
     */
    @Override
    public PageResult pageQueryEmployee(EmployeePageQueryDTO employeePageQueryDTO) {
        //启动分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());

        //通过 分页查询 实体类， 以及查询条件进行查询
        long total;
        List<Employee> records;
        try (Page<Employee> page = employeeMapper.pageQueryEmployee(employeePageQueryDTO)) {
            log.info("service:分页查询");
            //查询到的结果数量
            total = page.getTotal();
            //查询到的数据
            records = page.getResult();
        }

        return new PageResult(total, records);
    }

    /**
     * 员工登录
     *
     * @param employeeLoginDTO 员工登录信息 DTO
     * @return 员工信息
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getEmployeeByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //进行md5加密, 然后再进行比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (Objects.equals(employee.getStatus(), StatusConstant.DISABLE)) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 根据id查询员工信息(修改回显)
     *
     * @param employeeId 员工id
     * @return 员工信息
     */
    @Override
    public Employee getEmployeeById(Long employeeId) {
        Employee employee;
        employee = employeeMapper.getEmployeeById(employeeId);
        employee.setPassword("****");
        return employee;
    }
}
